package com.xiaotou.db.dao;

import java.io.Serializable;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository("commonDao")
public class CommonDAO extends HibernateDaoSupport {

    private static final Logger log = LoggerFactory.getLogger(CommonDAO.class);

    public void save(Object entity) {
        log.debug("saving Entity instance {}", entity);
        try {
            getHibernateTemplate().save(entity);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    public void update(Object entity) {
        log.debug("updating Entity instance {}", entity);
        try {
            getHibernateTemplate().save(entity);
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }

    public <T> T get(Class<T> entityClass, Serializable id) {
        log.debug("getting Entity instance {}, id={}", entityClass, id);
        try {
            return getHibernateTemplate().get(entityClass, id);
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public void delete(Object entity) {
        log.debug("deleting Entity instance {}", entity);
        try {
            getHibernateTemplate().delete(entity);
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

	@SuppressWarnings("unchecked")
	public <T> List<T> findByNameQuery(String queryName) {
		log.debug("find by Named Query: {}", queryName);
		try {
			return getHibernateTemplate().findByNamedQuery(queryName);
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
    public <T> List<T> findByNamedQuery(String queryName, Object... values) {
        log.debug("find by Named Query: {}", queryName);
        try {
            return getHibernateTemplate().findByNamedQuery(queryName, values);
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    @SuppressWarnings("unchecked")
    public <T> List<T> findByNamedQueryAndNamedParam(String queryName, String paramName, Object value) {
        log.debug("find by Named Query: {}", queryName);
        try {
            return getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramName, value);
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
}
